<template>
    <view class="register">
        <view>
            <h3 class="title">注册用户</h3>
            <u-form :model="form" ref="uForm" label-position="top"
                    :label-style="{color: '#00eaff',fontSize: '20rpx',lineHeight: '20rpx'}">
                <u-form-item prop="mobile" label="手机号">
                    <u-input v-model="form.mobile" type="number" placeholder="请输入手机号"
                             :custom-style="{
                                 color: '#ffffff',
                             }"/>
                </u-form-item>
                <u-form-item prop="password" label="密码">
                    <u-input v-model="form.password" type="password" placeholder="请输入密码"
                             :custom-style="{
                                 color: '#ffffff',
                             }"/>
                </u-form-item>
                <u-form-item prop="imgCode" label="验证码">
                    <u-input v-model="form.imgCode" type="number" placeholder="请输入验证码" maxlength="4"
                             :custom-style="{
                                 color: '#ffffff',
                             }"/>
                    <u-image width="30%" height="50rpx" :src="captchaDataUrl" @click="captchaLoaded"></u-image>
                </u-form-item>
                <u-form-item prop="captcha" label="短信验证码">
                    <u-input v-model="form.captcha" type="number" placeholder="请输入短信验证码" maxlength="6"
                             :custom-style="{
                                 color: '#ffffff',
                             }"/>
                    <u-verification-code seconds=60 ref="captcha" @change="captchaChange"></u-verification-code>
                    <u-button @tap="getCode" type="primary" size="mini">{{ tips }}</u-button>
                </u-form-item>
                <u-form-item prop="sharecode" label="邀请码（选填）">
                    <u-input v-model="form.sharecode" placeholder="请输入邀请码（选填）"/>
                </u-form-item>
                <u-form-item prop="agreement">
                    <u-checkbox-group>
                        <u-checkbox v-model="form.agreement" shape="circle">
                            <view style="color: #ffffff;font-size: 24rpx">我已满18岁，并同意《用户协议》和《隐私政策》</view>
                        </u-checkbox>
                    </u-checkbox-group>
                </u-form-item>
            </u-form>
            <view class="register-button">
                <!--                <u-button @click="toLogin" shape="circle" :plain="true" class="register-button-item">去登录</u-button>-->
                <u-button @click="register" class="register-button-item" type="success">注册</u-button>
                <view class="login">
                    已有账号？
                    <text @click="toLogin" class="login-text">立即登录</text>
                </view>
            </view>
        </view>
        <!-- 提示框 -->
        <u-toast ref="uToast"/>
    </view>
</template>
<script>
export default {
    name: 'register',
    data() {
        return {
            form: {
                mobile: '',
                password: '',
                imgCode: '',
                // 验证的key
                key: '',
                captcha: '',
                agreement: false,
            },
            captchaDataUrl: '', // 用于保存解码后的图片 URL
            tips: '',
        }
    },
    created() {
        this.fetchCaptcha()
    },
    methods: {
        //获取图形验证码
        async fetchCaptcha() {
            await this.$u.api.getCaptcha({
                event: 'create'
            }).then(res => {
                this.form.key = res.data.key
                const response = res.data.captcha
                this.captchaDataUrl = 'data:image/png;base64,' + response;
            })
        },
        //点击刷新验证码
        captchaLoaded() {
            // 触摸验证码图片刷新
            this.fetchCaptcha()
        },
        // 发送短信
        sendSms(callback) {
            if (this.form.mobile === '') {
                this.$u.toast('请输入手机号');
                return;
            }
            if (!this.$u.test.mobile(this.form.mobile)) {
                this.$u.toast('手机号码不正确');
                return;
            }
            if (!this.form.imgCode) {
                this.$u.toast('请输入图形验证码');
                return;
            }
            this.$u.api.smsSend({
                mobile: this.form.mobile,
                event: 'register',
                imgCode: this.form.imgCode,
                key: this.form.key
            }).then(res => {
                if (res.code !== 1) {
                    this.$u.toast(res.msg);
                    this.fetchCaptcha()
                    callback(false);
                } else {
                    callback(true);
                }
            });
        },

        // 发送短信按钮操作
        captchaChange(text) {
            this.tips = text;
        },
        // 获取验证码
        getCode() {
            this.sendSms((isValid) => {
                if (isValid) {
                    if (this.$refs.captcha.canGetCode) {
                        setTimeout(() => {
                            uni.hideLoading();
                            // 这里此提示会被this.start()方法中的提示覆盖
                            this.$refs.uToast.show({
                                title: '验证码已发送,请注意查收',
                                type: 'success'
                            });
                            // 通知验证码组件内部开始倒计时
                            this.$refs.captcha.start();
                        }, 1000);
                    } else {
                        this.$refs.uToast.show({
                            title: '倒计时结束后再发送',
                            type: 'error'
                        });
                    }
                }
            })
        },
        // 去登录
        toLogin() {
            // 关闭注册弹窗 打开登录弹窗
            this.$emit('toLogin');
        },
        // 注册
        register() {
            if (this.form.mobile === '' || this.form.password === '') {
                this.$u.toast('请输入手机号和密码');
                return;
            } else if (this.form.agreement === false) {
                this.$u.toast('请阅读并同意用户协议和隐私政策');
                return;
            }
            // 添加正则手机号验证
            if (!this.$u.test.mobile(this.form.mobile)) {
                this.$u.toast('手机号码不正确');
                return;
            }
            //添加密码验证
            if (!this.$u.test.rangeLength(this.form.password, [6, 18])) {
                this.$u.toast('密码长度在6-18之间');
                return;
            }
            // 验证码判断
            if (this.form.captcha === '') {
                this.$u.toast('请输入短信验证码')
            }
            // 注册
            this.$u.api.register({
                mobile: this.form.mobile,
                password: this.form.password,
                captcha: this.form.captcha,
                sharecode: this.form.sharecode !== '' ? this.form.sharecode : null,
            }).then(res => {
                if (res.code === 1) {
                    this.$refs.uToast.show({
                        title: res.msg,
                        type: 'success'
                    });
                    this.$emit('toLogin');
                } else {
                    this.fetchCaptcha()
                    this.$refs.uToast.show({
                        title: res.msg,
                        type: 'error'
                    });
                }
            })
        }


    }
}
</script>


<style scoped lang="scss">
.register {
    padding: 30rpx;
    background-color: #0f0e2d;

    .title {
        margin: 30rpx;
        text-align: center;
        color: #00eaff;
    }
}

.register-button {
    display: flex;
    align-items: center;
    flex-direction: column;
    padding-top: 30rpx;
    padding-bottom: 10rpx;

    .register-button-item {
        width: 85vw;
    }

    ::v-deep .u-btn {
        height: 75rpx;
        line-height: 75rpx;
    }

    .login {
        padding-top: 30rpx;

        .login-text {
            color: #00eaff;
        }
    }
}

::v-deep .u-type-success {
    background-color: #0f0e2d;
    border: none;
}
::v-deep .u-type-error{
    background-color: #0f0e2d;
    border:none;
}
</style>